/*jslint browser: true, nomen: true, es5: true*/
/*global $, jQuery, window, requirejs, require, define*/
(function (factory) {
    "use strict";
	if (typeof define === "function" && define.amd) {
		// AMD. Register as an anonymous module.
		define(["jquery", "jquery.ui"], factory);
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
    "use strict";
        
    $.widget("lhmcv.combobox", {
        defaultElement: "<input>",
        options: {
            appendTo: null,
            autoFocus: false,
            datalist: [],
            pkAttr: "pk",
            nameAttr: "name"
        },
        _create: function () {
            //this.element
            this.datalist = this.options.datalist;
            this.wrapper = $("<span>")
                .addClass("lhmcv-combobox");
            this.element.wrap(this.wrapper);
            this._createAutocomplete();
            this._createShowAllButton();
        },
        
        setDatalist: function (dict_list) {
            this.datalist =  dict_list;
            this.input.autocomplete({
                source: this._automcomplateSource(dict_list)
            });
        },
        
        _automcomplateSource: function (dict_list) {
            var source_array = [],
                index,
                length = dict_list.length;
            for (index = 0; index < length; index += 1) {
                source_array.push(dict_list[index][this.options.nameAttr]);
            }
            return source_array;
        },
        
        _createAutocomplete: function () {
            this.input = this.element//$("#" + this.element.attr("id"))
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: this._automcomplateSource(this.datalist)
                })
                .addClass("lhmcv-combobox-input ui-widget ui-widget-content ui-corner-left")
                .attr("title", "")
                .tooltip({
                    tooltipClass: "ui-state-highlight ui-corner-left"
                });
            this._on(this.input, {
                autocompleteselect: function (event, ui) {
                    this._trigger("select", event, ui);
                },

                autocompletechange: "_removeIfInvalid"
            });
            this._on(this.element, {
                focus: function () {
                    this.element
                        .tooltip("close")
                        .attr("title", "")
                        .removeAttr('style');
                }
            });
        },

        _createShowAllButton: function () {
            var input = this.input,
                wasOpen = false;

            this.button = $("<a>")
                .attr("tabIndex", -1)
                .attr("title", "显示所有选项")
                .tooltip()
                .insertAfter(input)
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .removeClass("ui-corner-all")
                .addClass("lhmcv-combobox-toggle ui-corner-right")
                .mousedown(function () {
                    wasOpen = input.autocomplete("widget").is(":visible");
                })
                .click(function () {
                    input.focus();
                    // Close if already visible
                    if (wasOpen) {
                        return;
                    } else {
                        // Pass empty string as value to search for, displaying all results
                        input.autocomplete("search", "");
                    }
                });
        },
        
        _searchAttr: function (find_attr_name, find_value, aim_attr_name) {
            var datalist = this.datalist,
                index,
                length = datalist.length,
                array_item;
            for (index = 0; index < length; index += 1) {
                array_item = datalist[index];
                if (array_item[find_attr_name] === find_value) {
                    return array_item[aim_attr_name];
                }
            }
            return undefined;
        },
        
        _removeIfInvalid: function (event, ui) {
            // Selected an item, nothing to do
            if (ui.item) {
                this.element
                    .tooltip("close")
                    .attr("title", "")
                    .removeAttr('style');
                return;
            }
            var value = this.input.autocomplete("instance")._value(),
                searchResult = this._searchAttr(this.options.nameAttr, value, this.options.pkAttr),
                original_title;
            if (searchResult !== undefined) {
                this.element
                    .tooltip("close")
                    .attr("title", "")
                    .removeAttr('style');
                return;
            } else {
                this.element
                    .val("")
                    .css({
                        "background-color": "lightgoldenrodyellow",
                        "border-color": "red"
                    })
                    .attr("title", value + " 不存在")
                    .tooltip("open");
				this._delay(function () {
					this.element.tooltip("close").attr("title", "");
				}, 1500);
                this.input.autocomplete("instance").term = "";
            }
        },

        _destroy: function () {
            this.element.unwrap();
            this.wrapper.remove();
            this.input._destroy();
            this.button._destroy();
        }
    });
    
    $.datepicker.setDefaults({
        monthNames:  ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
        monthNamesShort:  ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
        dayNamesMin: [ "日", "一", "二", "三", "四", "五", "六"],
        firstDay: 1,
        showWeek: true,
        weekHeader: "周",
        showButtonPanel: true,
        currentText: "今天",
        closeText: "确定",
        showOn: "both",
        changeMonth: true,
        changeYear: true,
        dateFormat: "yy-mm-dd",
        buttonText: "...",
        showMonthAfterYear: true
    });
    
    $.widget("lhmcv.iNavi", {
        defaultElement: "<ul>",
        options: {
            animation: 150,
            width: "120px",
            icons: {
                activeHeader: "ui-icon-triangle-1-s",
                header: "ui-icon-triangle-1-e"
            }
        },
        _create: function () {
            this.element.addClass('lhmcv-navi ui-state-active');
            this.element.find('ul')
                .addClass('lhmcv-navi-group-collapsed');
            this.element.find('li').children('a')
                .addClass('lhmcv-navi-link');
            this.element.find('li').has("ul")
                .attr('aria-expanded', 'false')
                .children('a')
                .removeClass('lhmcv-navi-link')
                .addClass('lhmcv-navi-parent-collapsed');
            //bind the custom events
            this._on(this.element, {
                click: function (event) {
                    var target = $(event.target);
                    if (target.next().is('ul')) {
                        this._toggle(target);
                        //return click event false because it's a tree node (folder)
                        return false;
                    }
                }
            });
        },
        _expand: function (targetJqueryElement) {
            var target = targetJqueryElement,
                slideDonwTime = this.options.animation;
            target.removeClass('lhmcv-navi-parent-collapsed')
                .addClass('lhmcv-navi-parent-active');
            target.next()
                .removeAttr('style')
                .hide()
                .removeClass('lhmcv-navi-group-collapsed')
                .slideDown(slideDonwTime);
            target.parent().attr('aria-expanded', 'true');
        },
        _collapse: function (targetJqueryElement) {
            var target = targetJqueryElement,
                slideDonwTime = this.options.animation;
            target.removeClass('lhmcv-navi-parent-active')
                .addClass('lhmcv-navi-parent-collapsed');
            target.next()
                .removeAttr('style')
                .slideUp(slideDonwTime, function () {
                    target.next().addClass('tree-group-collapsed');
                });
            target.parent().attr('aria-expanded', 'false');
        },
        _toggle: function (targetJqueryElement) {
            var target = targetJqueryElement;
            if (target.parent().attr('aria-expanded') === "false") {
                this._expand(target);
            } else {
                this._collapse(target);
            }
        }
    });
}));